package com.seeyon.apps.kkSample.utils;

import com.seeyon.apps.cip.binding.manager.CIPUserConfigManager;
import com.seeyon.apps.cip.binding.manager.ThirdpartyUserTransformationManager;
import com.seeyon.apps.cip.constants.CIPErrorMessage;
import com.seeyon.apps.cip.constants.CIPErrorMessage.MessageStatus;
import com.seeyon.apps.cip.enums.GetModeEnum;
import com.seeyon.apps.cip.manager.RegisterManager;
import com.seeyon.apps.cip.messageandpending.manager.MessageOrPendingCacheManager;
import com.seeyon.apps.cip.messageandpending.po.MessageOrPending;
import com.seeyon.apps.cip.po.RegisterPO;
import com.seeyon.apps.cip.po.ThirdPendingPO;
import com.seeyon.apps.cip.util.CIPUtil;
import com.seeyon.apps.cip.vo.ThirdPendingVO;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.Strings;
import org.apache.commons.logging.Log;

import java.util.Date;
import java.util.Map;

/**
 * 第三方待办处理
 *
 * @author
 */
public final class PendingUtil {
	private static final Log LOG = CtpLogFactory.getLog(PendingUtil.class);
	private static final RegisterManager registerManager = (RegisterManager) AppContext.getBean("registerManager");
	private static final MessageOrPendingCacheManager messageOrPendingCacheManager = (MessageOrPendingCacheManager) AppContext.getBean("messageOrPendingCacheManager");
	private static CIPUserConfigManager cipUserConfigManager = null;

	private static CIPUserConfigManager getCIPUserConfigManager() {
		if (null == cipUserConfigManager) {
			cipUserConfigManager = (CIPUserConfigManager) AppContext.getBean("cipUserConfigManager");
		}
		return cipUserConfigManager;
	}

	public static CIPErrorMessage checkUpdatePending(String registerCode, String taskId, int state, int subState) {
		CIPErrorMessage error = new CIPErrorMessage();
		if (Strings.isBlank(registerCode) || Strings.isBlank(taskId)) {
			error.addErrorMsg(MessageStatus.pendingDataErr, taskId + " registerCode,taskId参数都不允许为空！");
		}
		if (state != 1 && state != 2) {
			error.addErrorMsg(MessageStatus.pendingDataErr, taskId + " state参数传递错误，只能是1/2！");
		}
		if (!(subState >= 0 && subState <= 3)) {
			error.addErrorMsg(MessageStatus.pendingDataErr, taskId + " subState参数传递错误，只能是0/1/2/3同意已办/不同意已办/取消/驳回！");
		}
		return error;
	}

	public static CIPErrorMessage checkPending(Map<String, Long> thirdBatchMap, Map<String, RegisterPO> batchMap, String registerCodeGlobe, ThirdPendingVO pv, GetModeEnum modeEnum, Long... memberId) throws BusinessException {
		CIPErrorMessage msg = new CIPErrorMessage();
		if (Strings.isBlank(pv.getTaskId())) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "待办第三方id不能为空，待办标题:" + pv.getTaskId());
		}
		if (Strings.isBlank(pv.getTitle())) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "待办标题不能为空，待办第三方id:" + pv.getTaskId());
		}

		String registerCode = Strings.isBlank(registerCodeGlobe) ? pv.getRegisterCode() : registerCodeGlobe;
		if (Strings.isBlank(registerCode)) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "系统注册编码不能为空，待办第三方id:" + pv.getTaskId());
		}

		if (!msg.isSuccess()) {
			return msg;
		}
		RegisterPO register = null;
		if (batchMap == null) {
			register = registerManager.getRegisterIdByCode(registerCode);
		} else {
			register = batchMap.get(registerCode);
		}
		if (register == null) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "系统注册编码不能为空，待办第三方id:" + pv.getTaskId());
			return msg;
		}
		MessageOrPending messagePO = messageOrPendingCacheManager.getMessageOrPendingCfg(register.getId(), "P");
		if (messagePO == null) {
			msg.addErrorMsg(MessageStatus.pendingNotEnable, "第三方注册编码：" + registerCode);
			return msg;
		}
		if (messagePO.getGetMode() != modeEnum.getKey()) {
			msg.addErrorMsg(MessageStatus.pendingErrorModule,
					"第三方注册编码：" + pv.getRegisterCode() + " 模式：" + modeEnum.getText());
		}
		boolean isPoint = CIPUtil.isPonint2Point(registerCode);
		if (Strings.isBlank(pv.getThirdReceiverId()) & isPoint) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "待办接收人id不能为空，待办第三方id:" + pv.getTaskId());
			return msg;
		}
		Long receiver;
		try {
			receiver = getCIPUserConfigManager().getMemberIdByNoneBinding(registerCode, pv.getNoneBindingReceiver());
		} catch (Exception e) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "免绑定失败:" + pv.getNoneBindingReceiver());
			return msg;
		}
		if (receiver == null) {
			receiver = getMemberByMapper(thirdBatchMap, pv.getThirdReceiverId(), String.valueOf(register.getId()));
		}
		if (receiver == null || receiver == -1L) {
			msg.addErrorMsg(MessageStatus.pendingDataErr, "请检查用户绑定：未找到待办接收人," + (Strings.isNotBlank(pv.getThirdReceiverId()) ? pv.getThirdReceiverId() : "") + " " + (Strings.isNotBlank(pv.getNoneBindingReceiver()) ? pv.getNoneBindingReceiver() : ""));
			return msg;
		}
		if (memberId != null && memberId.length > 0) {
			if (!receiver.equals(memberId[0])) {
				msg.addErrorMsg(MessageStatus.pendingDataErr, "读取待办不是当前登录人的待办:" + pv.getTaskId() + " " + pv.getThirdReceiverId());
			}
		}
		if (pv.getTitle().length() > 4000) {//客开，待办标题扩展至4000
			msg.addErrorMsg(MessageStatus.pendingDataErr, "待办标题超长,不可超过4000");
		}
		return msg;

	}

	private static Long getMemberByMapper(Map<String, Long> thirdBatchMap, String memberId, String registerId) {
		Long receiver = -1L;
		if (thirdBatchMap != null) {
			receiver = thirdBatchMap.get(ThirdpartyUserTransformationManager.getInstance().getMemberByThirdUserId(registerId, memberId));
		} else {
			receiver = ThirdpartyUserTransformationManager.getInstance().getMemberId(registerId, memberId);
		}
		return receiver;
	}

	public static ThirdPendingPO changePending(ThirdPendingVO vo, Map<String, RegisterPO> batchMap, Map<String, Long> thirdBatchMap) throws BusinessException {
		RegisterPO register = null;
		if (batchMap == null) {
			register = registerManager.getRegisterIdByCode(vo.getRegisterCode());
		} else {
			register = batchMap.get(vo.getRegisterCode());
		}
		ThirdPendingPO po = new ThirdPendingPO();
		po.setIdIfNew();
		po.setAppParam(vo.getAppParam());
		po.setContent(vo.getContent());
		po.setContentType(vo.getContentType());
		try {
			Date date = DateUtil.parse(vo.getCreationDate(), DateUtil.YEAR_MONTH_DAY_HOUR_MINUTE_SECOND_PATTERN);
			if (null == date) {
				date = new Date();
			}
			po.setCreationDate(date);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			po.setCreateDate(new Date());
		}
		po.setH5url(vo.getH5url());
		po.setSenderName(vo.getSenderName());
		po.setState(vo.getState());
		po.setSubState(vo.getSubState());
		po.setTaskId(vo.getTaskId());
		po.setThirdReceiverId(vo.getThirdReceiverId());
		Long receiver = null;
		try {
			receiver = getCIPUserConfigManager().getMemberIdByNoneBinding(vo.getRegisterCode(), vo.getNoneBindingReceiver());
		} catch (Exception e1) {
			LOG.warn("待办接收人未匹配：" + vo.getNoneBindingReceiver());
			return null;
		}
		if (receiver == null) {
			receiver = getMemberByMapper(thirdBatchMap, vo.getThirdReceiverId(), String.valueOf(register.getId()));
		}
		po.setReceiverId(receiver);
		Long sendId = null;
		try {
			sendId = getCIPUserConfigManager().getMemberIdByNoneBinding(vo.getRegisterCode(), vo.getNoneBindingSender());
		} catch (Exception e) {
			LOG.warn("待办发起人未匹配：" + vo.getNoneBindingSender());
		}

		if (null == sendId) {
			sendId = getMemberByMapper(thirdBatchMap, vo.getThirdSenderId(), String.valueOf(register.getId()));
		}
		po.setSenderId(sendId == null ? -1L : sendId);
		po.setThirdSenderId(vo.getThirdSenderId());
		po.setTitle(vo.getTitle());
		po.setClassify(vo.getClassify());
		po.setUrl(vo.getUrl());
		po.setRegisterId(register.getId());
		po.setCreateDate(new Date());
		po.setUpdateDate(new Date());
		po.setAppParam(CIPUtil.getAppParam4Json(register, po.getAppParam(), po.getContent()));
		po.setReadState(0);
		return po;
	}

}
